define(['jquery', 'jquerymobile', 'net', 'dialogs', 'newsroomDetailed', 'activity_details', 'activity_register'], function($, m, net, dia, newsdetail, activityDetail, activityRegister) {
    // Nick added for pull to refresh start
    var isScrolling = false,
        iScroll_news = {
        myScroll: null,
        allowGetMore: true,
        pullDownAction: function() {
            getNews(true);
        },
        pullUpAction: function() {
            getNews();
        },
        loaded: function(wrapper) {
            var $wrapper = $("#" + wrapper),
                $pullDownEl = $wrapper.find("#pullDown"),
                $pullDownLabel = $pullDownEl.find(".pullDownLabel"),
                pullDownOffset = $pullDownEl[0].offsetHeight,
                $pullUpEl = $wrapper.find("#pullUp"),
                $pullUpLabel = $pullUpEl.find(".pullUpLabel"),
                $pullUpIcon = $pullUpEl.find(".pullUpIcon"),
                pullUpOffset = $pullUpEl[0].offsetHeight;

            iScroll_news.myScroll = new iScroll(wrapper, {
                hScrollbar: false,
                vScrollbar: false,
                useTransition: true,
                topOffset: pullDownOffset,
                onRefresh: function () {
                    if ($pullDownEl.hasClass("loading")) {
                        $pullDownEl.removeClass("loading");
                        $pullDownLabel.text("Pull down to refresh...");
                    } else if ($pullUpEl.hasClass("loading")) {
                        $pullUpEl.removeClass("loading");
                        if (iScroll_news.allowGetMore) {
                            $pullUpIcon.show();
                            $pullUpLabel.text("Pull up to load more...");
                        } else {
                            $pullUpIcon.hide();
                            $pullUpLabel.text("No more articles available!");
                        }
                    }
                },
                onScrollMove: function () {
                    if (this.y > 5 && !$pullDownEl.hasClass("flip")) {
                        $pullDownEl.addClass("flip");
                        $pullDownLabel.text("Release to refresh...");
                        this.minScrollY = 0;
                    } else if (this.y < 5 && $pullDownEl.hasClass("flip")) {
                        $pullDownEl.removeClass("flip");
                        $pullDownLabel.text("Pull down to refresh...");
                        this.minScrollY = -pullDownOffset;
                    } else if (this.y < (this.maxScrollY - 5) && !$pullUpEl.hasClass("flip")) {
                        if (iScroll_news.allowGetMore) {
                            $pullUpEl.addClass("flip");
                            $pullUpLabel.text("Release to refresh...");
                            this.maxScrollY = this.maxScrollY;
                        }
                    } else if (this.y > (this.maxScrollY + 5) && $pullUpEl.hasClass("flip")) {
                        if (iScroll_news.allowGetMore) {
                            $pullUpEl.removeClass("flip");
                            $pullUpLabel.text("Pull up to load more...");
                            this.maxScrollY = pullUpOffset;
                        }
                    }
                    isScrolling = true;
                },
                onScrollEnd: function () {
                    if ($pullDownEl.hasClass("flip")) {
                        $pullDownEl.attr("class", "loading");
                        $pullDownLabel.text("Loading...");
                        iScroll_news.pullDownAction();
                    } else if ($pullUpEl.hasClass("flip")) {
                        if (iScroll_news.allowGetMore) {
							iScroll_news.allowGetMore = false;
                            $pullUpEl.attr("class", "loading");
                            $pullUpLabel.text("Loading...");
                            iScroll_news.pullUpAction();
                        }
                    }
                    setTimeout(function() {
                        isScrolling = false;
                    }, 500);
                }
            });
        }
    };
    // Nick added for pull to refresh end
    // 查询到的新闻数据
    var v_news = [];

    // 当前页数
    var currentPageNumer = 1;

    // 控制底部事件激发开关 0表示开 非0表示关闭时间
    var scrollButtomOn = 0;

    // 上一次滚动的位置
    var scrollTopBefore = 0;

    // 补充0
    function pad(n, width, z) {
        z = z || '0';
        n = n + '';
        return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
    }

    /**
     * 展示过滤按钮样子
     */
    function displayFilter() {
        if ((!$.isEmptyObject(localStorage['selected_tags'])) &&
            (localStorage['selected_tags'].toString().split(',').length < 9)) {
            $('#newsroom_btn_filter').removeClass('filter').addClass('filterOn');
        } else {
            $('#newsroom_btn_filter').removeClass('filterOn').addClass('filter');
        }

    }

    /**
     * 禁用滚动时间3秒
     */
    function disableScrollBottom() {
        scrollButtomOn = 3;
        var timer = setInterval(function() {
            if (scrollButtomOn == 0) {
                clearInterval(timer);
                return;
            }

            scrollButtomOn--;

        }, 1000);
    }

    function TagtoLit(tag) {
        if (tag == 'Center Operations')
            return 'OPS';
        else if (tag == 'Technical Development')
            return 'TD';
        else if (tag == 'Innovation')
            return 'INNO';
        else if (tag == 'Human Resources')
            return 'HR';
        else if (tag == 'Trade Union')
            return 'GTU';
        else if (tag == 'Finance')
            return 'FIN';
        else if (tag == 'Corporate Sustainability')
            return 'CS';
        else if (tag == 'Communications')
            return 'COMM';
        else {
            console.assert(false, '标签 %o 不存在 ', tag );
        }
    }

    //创建活动
    function creatActivity(banner, subject, brifContent, time, day, venue, tags) {
        console.assert(subject != null, '活动标题 %o 不能为空', subject);
        console.assert(brifContent != null, '活动简介 %o 不能为空', brifContent);
        console.assert(time != null, '活动时间 %o 不能为空', time);
        console.assert(day != null, '活动日期 %o 不能为空', day);
        console.assert(venue != null, '活动地点 %o 不能为空', venue);
        console.assert(tags != null, '活动标签 %o 不能为空', tags);
        var activityBrifContent = brifContent;
        //超过160的字符就显示...
        if (activityBrifContent.length > 160) {
            activityBrifContent = brifContent.substring(0, 160) + '...';
        }

        var html_tags = '';
        if(tags != null) {
            $.each(tags, function(index, val) {
                if (val.name == 'Communications')
                    html_tags += '\<span class="spanTag" style="background-color: rgb(77, 134, 176);">COMM</span>  ';
                if (val.name == 'Corporate Sustainability')
                    html_tags += '\<span class="spanTag" style="background-color: rgb(137, 217, 78);">CS</span>  ';
                if (val.name == 'Finance')
                    html_tags += '\<span class="spanTag" style="background-color: rgb(219, 218, 0);">FIN</span>  ';
                if (val.name == 'Trade Union')
                    html_tags += '\<span class="spanTag" style="background-color: rgb(147, 182, 164);">GTU</span>  ';
                if (val.name == 'Human Resources')
                    html_tags += '\<span class="spanTag" style="background-color: rgb(230, 170, 0);">HR</span>  ';
                if (val.name == 'Innovation')
                    html_tags += '\<span class="spanTag" style="background-color: rgb(76, 176, 170);">INNO</span>  ';
                if (val.name == 'Center Operations')
                    html_tags += '\<span class="spanTag" style="background-color: rgb(138, 116, 122);">OPS</span>  ';
                if (val.name == 'Technical Development')
                    html_tags += '\<span class="spanTag" style="background-color: rgb(121, 110, 172);">TD</span>  ';
            });
        }

        var html = '\<li style="border: 0px;padding: 0px;margin-bottom:10px">\
            <div id="newsroom_detail_sele">\
				<div style="width: 100%" >\
					<img src="'+banner+'"\ style="width: 100%" alt=""/>\
				</div>\
                <label style="margin: 10px; font-size: 18px; white-space:normal;color: #404040">'+ subject +'\</label>\
                <div style="margin: 10px">\
                    <div style="white-space:normal;font-weight: normal;font-size: 12px;color: #404040">'+ activityBrifContent.replace(/\n/g,'</br>') +'\</div>\
                </div>\
                <div style="margin: 10px;font-size: 11px;color: #404040;">\
                    <span style="display: block;white-space: normal;">'+ time +'\</span>\
                    <span style="display: block;white-space: normal;">'+ day +'\</span>\
                    <span style="display: block;white-space: normal;">'+ venue +'\</span>\
                </div>\
                <div id="newsroom_detail_sele_tags" style="margin: 10px;width: auto;white-space: normal;">\
                    '+ html_tags +'\
                \</div>\
                <div style="border-bottom: solid 1px;border-bottom-color: #C0C0C0;width: 100%;clear:left;padding-top:10px;"></div>\
            </div>\
            <div id="newsroom_nowRegister" style="margin: 10px 0px 10px 10px;width: auto;height: 28px;line-height: 28px;">\
                <div style="padding: 0px;">\
                    <span style="width: 90%;float: left;font-size:14px">Register now</span>\
                    <span class="right_chevron" style="width: 10%;float: right;height: 25px"></span>\
                </div>\
            </div>\
            </li>';
        return html;
    }

    /**
     * 展示内容
     * @param content
     */
    // Nick removed for pull to refresh start
    // function showContent(content) {
    //     console.assert(content.types != null, '要展示的内容都没有类型啊');

    //     if (content.types == 'new') {
    //         getNewsHTML(content);
    //     } else if (content.types == 'activity') {
    //         getAcitvityHTML(content);
    //     } else {
    //         console.assert(false, '除了新闻和活动，目前不会有%s类型。', content.types);
    //     }
    // }
    // Nick removed for pull to refresh end
    // Nick added for pull to refresh start
    function showContent(contentList, refresh) {
        var contentHTML = "",
            contentArray = [],
            $newsroom_listview = $("#newsroom_listview_news");
        $.each(contentList, function(i, content) {
            console.assert(content.types != null, '要展示的内容都没有类型啊');

            if (content.types == 'new') {
                contentArray.push(getNewsHTML(content));
            } else if (content.types == 'activity') {
                contentArray.push(getAcitvityHTML(content));
            } else {
                console.assert(false, '除了新闻和活动，目前不会有%s类型。', content.types);
            }
        });
        contentHTML = contentArray.join("");
        if (refresh) {
            $newsroom_listview.html(contentHTML);
        } else {
            $newsroom_listview.append(contentHTML);
        }
        $newsroom_listview.listview("refresh");
        if (iScroll_news.myScroll == null) {
            iScroll_news.loaded("news_wrapper");
        }
    }
    // Nick added for pull to refresh end

    /**
     * 获得新闻HTML
     * @param news
     */
    function getNewsHTML(news) {
        news.TTagses.sort(function(a, b) {

            if (TagtoLit(a.name) > TagtoLit(b.name))
                return 1;
            else if (TagtoLit(a.name) < TagtoLit(b.name))
                return -1;

            return 0;
        });

        var date = new Date(news.approvalTime * 1000);
        var month = getMonthString(date.getMonth());
        var time = 'Posted on ' + date.getDate() + " " + month + " " + date.getFullYear();
        var li = createNews(news.pic, news.title, news.briefContent, time, news.TTagses);
        // Nick removed for pull to refresh start
        // $('#newsroom_listview_news').append(li);
        // $('#newsroom_listview_news').listview( "refresh" );
        // Nick removed for pull to refresh end
        // Nick added for pull to refresh start
        return li;
        // Nick added for pull to refresh end
    }

    /**
     * 获得活动HTML
     * @param activity
     */
    function getAcitvityHTML(activity) {
        activity.tags.sort(function(a, b) {

            if (TagtoLit(a.name) > TagtoLit(b.name))
                return 1;
            else if (TagtoLit(a.name) < TagtoLit(b.name))
                return -1;

            return 0;
        });

        var startDate = new Date(activity.startTime * 1000);
        var endDate = new Date(activity.endTime * 1000);
        var startTime = 'Start: ' + pad(startDate.getHours(), 2) + ':' + pad(startDate.getMinutes(),2) + ', ' + startDate.getDate() + " " + getMonthString(startDate.getMonth()) + " " + startDate.getFullYear();
        var endTime = 'End: ' + pad(endDate.getHours(),2) + ':' + pad(endDate.getMinutes(),2) + ', ' + endDate.getDate() + " " + getMonthString(endDate.getMonth()) + " " + endDate.getFullYear();
        var venue = 'Venue: ' + activity.venue;
        var li = creatActivity(activity.banner, activity.subject, activity.briefContent,startTime ,endTime , venue, activity.tags);
        // Nick removed for pull to refresh start
        // $('#newsroom_listview_news').append(li);
        // $('#newsroom_listview_news').listview("refresh");
        // Nick removed for pull to refresh end
        // Nick added for pull to refresh start
        return li;
        // Nick added for pull to refresh end
    }

    function getMonthString(month) {
		month = month + 1;
        if (month == 1)
            return 'Jan';
        else if (month == 2)
            return 'Feb';
        else if (month == 3)
            return 'Mar';
        else if (month == 4)
            return 'Apr';
        else if (month == 5)
            return 'May';
        else if (month == 6)
            return 'June';
        else if (month == 7)
            return 'July';
        else if (month == 8)
            return 'Aug';
        else if (month == 9)
            return 'Sept';
        else if (month == 10)
            return 'Oct';
        else if (month == 11)
            return 'Nov';
        else if (month == 12)
            return 'Dec';
        else {
            console.assert(false, '月份 %o 不存在 ', month );
        }
    }

    // 获得新闻
    // Nick removed for pull to refresh start
    // function getNews() {
    // Nick removed for pull to refresh end
    // Nick added for pull to refresh start
    function getNews(refresh) {
        if (refresh) {
            currentPageNumer = 1;
            v_news = [];
        }
    // Nick added for pull to refresh end
        var postData = {};
        postData['pager.pageNo'] = currentPageNumer;
        postData['pager.pageSize'] = 5;
        postData['userId'] = q['user'].userId;
        if ((!$.isEmptyObject(localStorage['selected_tags'])) &&
            (localStorage['selected_tags'].toString().split(',').length > 0) &&
			(localStorage['selected_tags'].toString().split(',').length < 9)) {
            postData['tagNames'] = localStorage['selected_tags'].toString().substr(0, (localStorage['selected_tags'].length - 1));
        }
        if ((!$.isEmptyObject($('#newsroom_header_searchbar')))
            && (!$.isEmptyObject($('#newsroom_header_searchbar').val())))
            postData['keyword'] = $('#newsroom_header_searchbar').val();
        // 获取新闻
        net.post('news/listNewsActivitys', postData, function(error){
        }, function(response){
            // Nick added for pull to refresh start
            var newsList = response.data.news,
                newsListLength = newsList.length;
            // Nick added for pull to refresh end
            if (response.code != 0) {

            } else {
                // Nick removed for pull to refresh start
                // if (response.data.news.length < 1) {
                //     var li = '\<li style="text-align: center;font-weight: normal;font-size: 14px;color: #404040;background-color: rgba(0,0,0,0);border: none;text-shadow: none;">No more articles available!</li>';
                //     $('#newsroom_listview_news').append(li);
                //     $('#newsroom_listview_news').listview( "refresh" );
                //     $('#news_content').off('scroll');
                // } else {
                //     v_news = v_news.concat(response.data.news);

                //     // 看是新闻还是活动
                //     $.each(response.data.news, function(i, content) {
                //         showContent(content);
                //     });
                // Nick removed for pull to refresh end
                // Nick added for pull to refresh start
                if (newsListLength > 0) {
                    v_news = v_news.concat(newsList);
                    showContent(newsList, refresh);
                // Nick added for pull to refresh end

                    currentPageNumer++;
                }else{
					if(refresh){
						$("#newsroom_listview_news").html("");
					}else{
						$("#newsroom_listview_news").append("");
					}
				}
                // Nick added for pull to refresh start
                var $pullUpEl = $("#news_wrapper").find("#pullUp"),
                    $pullUpLabel = $pullUpEl.find(".pullUpLabel"),
                    $pullUpIcon = $pullUpEl.find(".pullUpIcon");
                if (refresh) {
					if(newsListLength == 1){
						$pullUpIcon.hide();
                        $pullUpLabel.text("No more articles available!");
					}else if(newsListLength == 0){
						$pullUpIcon.hide();
						$pullUpEl.hide();
					}else{
						$pullUpLabel.text("Pull up to load more...");
						$pullUpIcon.show();
						$pullUpEl.show();
					}           
                    if (iScroll_news.myScroll.y !== 0) {
                        iScroll_news.myScroll.y = 0;
                    }
                }
                if (newsListLength < 1) {
                    iScroll_news.allowGetMore = false;
                } else {
                    iScroll_news.allowGetMore = true;
                }
                setTimeout(function() {
                    iScroll_news.myScroll.refresh();
					if(newsListLength == 0){
						$pullUpEl.show();
						$pullUpIcon.hide();
                        $pullUpLabel.text("No more articles available!");						
					}
                    disableClickEvent(false);
                }, 800);
                window.shouldPageRefresh.newsroom = false;
                window.shouldPageRefresh.activities = true;
                // Nick added for pull to refresh end
            }
        });
    }

    // 创建新闻
    function createNews(img, title, content, timestamp, tags) {
        console.assert(img != null, '新闻图片不能为空：%o', img);
        console.assert(title != null, '新闻标题不能为空：%o', title);
        console.assert(content != null, '新闻内容简介不能为空：%o', content);
        console.assert(timestamp != null, '新闻发布时间不能为空：%o', timestamp);
        console.assert(tags != null, '新闻标签不能为空：%o', tags);
        var newContent = content;
//        超过160的字符显示...
        if (newContent.length > 160)
            newContent = content.substring(0, 160) + '...';


        var html_tags = '';

        if (tags != null) {
            $.each(tags, function(index, val) {
                if (val.name == 'Communications')
                    html_tags += '\<span class="spanTag" style="background-color: rgb(77, 134, 176);">COMM</span>  ';
                if (val.name == 'Corporate Sustainability')
                    html_tags += '\<span class="spanTag" style="background-color: rgb(137, 217, 78);">CS</span>  ';
                if (val.name == 'Finance')
                    html_tags += '\<span class="spanTag" style="background-color: rgb(219, 218, 0);">FIN</span>  ';
                if (val.name == 'Trade Union')
                    html_tags += '\<span class="spanTag" style="background-color: rgb(147, 182, 164);">GTU</span>  ';
                if (val.name == 'Human Resources')
                    html_tags += '\<span class="spanTag" style="background-color: rgb(230, 170, 0);">HR</span>  ';
                if (val.name == 'Innovation')
                    html_tags += '\<span class="spanTag" style="background-color: rgb(76, 176, 170);">INNO</span>  ';
                if (val.name == 'Center Operations')
                    html_tags += '\<span class="spanTag" style="background-color: rgb(138, 116, 122);">OPS</span>  ';
                if (val.name == 'Technical Development')
                    html_tags += '\<span class="spanTag" style="background-color: rgb(121, 110, 172);">TD</span>  ';
            });
        }

        if (html_tags.length == 0) {
            html_tags = '\<span style="height: 35px;"> &nbsp; </span>';
        }

        var html = '\<li  style="border: 0px;padding: 0px;margin-bottom:10px">\
            <div style="width: 100%" >\
                <img src="'+img+'"\ style="width: 100%" alt=""/>\
            </div>\
            <label style="margin: 10px; font-size: 18px; white-space:normal;color: #404040">'+title+'\</label>\
            <div style="margin: 10px">\
                <div style="white-space:normal;font-weight: normal;font-size: 12px;color: #404040">'+newContent.replace(/\n/g,'</br>')+'\</div>\
            </div>\
            <div style="margin: 30px 10px 10px 10px">\
                <span style="font-size: 10px;color: #808080;white-space: normal;">'+timestamp+'\</span>\
            </div>\
            <div style="border-bottom: solid 1px;border-bottom-color: #C0C0C0;width: 100%;"></div>\
            <div style="margin-left: 10px; width: auto;white-space: normal;">\
            '+html_tags+'\
            \</div>\
            <div style="clear:left; width: 100%;height:10px;"></div>\
        </li>';

        return html;
    }

    // 点击菜单按钮出现菜单

    $('#newsroom_btn_menu').on('click', function(evt) {
        $('.ui-panel-inner').css({'padding':'0px'});
        $('.push_nees_opacity').css('min-height',$(window).height());
//        $('#push-ul').attr('height',$(window).height());
        $('#news_content').css('max-height',$(window).height()-40);
        $('#panel_menu').css('min-height',$(window).height());
        $('#push_ul').css('min-height',$(window).height());
        $('#auto_height').css('min-height',$(window).height()-406);
        console.log($('#panel_menu').css('min-height'));
        console.log($('#push_ul').css('min-height'));
        console.log($('#auto_height').css('height'));
        var username = localStorage['username'] + '!';
        $("#push_username").html(username);
        $( "#panel_menu" ).panel( "open" );
    });

    // 点击新闻项，菜单隐藏
    $('#push_newsroom').on('click', function(evt) {
        $( "#panel_menu" ).panel( "close" );
    });
	$('#push_AR').on('click', function(evt) {
        cordova.exec(function(){console.log("success")}, function(){console.log("error")}, "ShowVideoPlaybackView", "showVideoPlaybackView", []);
    });
	$('#push_Laisee').on('click', function(evt) {
		//Green Laisee entrance
		var cuser = null;
        if (localStorage.getItem('login_user')!=null) {
            cuser = JSON.parse(localStorage.getItem('login_user'));
        } else {
            console.assert(false, '还没登录，没有用户信息可填写');
        }
        cordova.exec(function(){console.log("success")}, function(){console.log("error")}, "OpenGreenLaisee", "openGreenLaisee", [JSON.stringify({"account": ""+cuser.staffId+"", "fullName": ""+cuser.english_name+"", "secureToken": "", "location": "CN"})]);
    });

    // 点击注销，返回登录
    $('#push_logon').on('click', function(evt) {
        $.mobile.newChangePage('#logon',{transition: "slide",reverse: true,changeHash: false});

        //注销用户后复选框清空
        $('#all_check').removeClass('sel').addClass('nor');
        $('div[name="sbox"]').each(function(index, val) {
            $(val).removeClass('sel').addClass('nor');
        });
        // Nick added for pull to refresh start
        cleanUpListItems();
        $(".wrapper").find("#pullUp").hide();
        window.shouldPageRefresh.newsroom = true;
        window.shouldPageRefresh.activities = true;
        // Nick added for pull to refresh end
    });



    // 点击某一个新闻
    $('#newsroom_listview_news').on('click', 'li', function(evt) {
        // Nick disable click event for scrolling start
        if (isScrolling) return false;
        // Nick disable click event for scrolling end
        console.log('暂时保存住的新闻');
        console.log(v_news);
		window.disableTouch = true;
        if (v_news[$(this).index()].types == 'new') {
            newsdetail.showDetailWithNews(v_news[$(this).index()]);
            $.mobile.newChangePage("#newsroom_detailed",{ transition: "slide",reverse: false,changeHash: false});
        } else if (v_news[$(this).index()].types == 'activity') {

        } else {
            console.assert(false, '除了新闻和活动，目前不会有%s类型。', v_news[$(this).index()].types);
        }
    }).on('click', '#newsroom_detail_sele', function(evt) {
        // Nick disable click event for scrolling start
        if (isScrolling) return false;
        // Nick disable click event for scrolling end
        console.log('当前选中的活动 %o', v_news[$(this).parent().index()]);
        activityDetail.showDetailWithActivity(v_news[$(this).parent().index()]);
        activityDetail.from('#newsroom');
        $.mobile.newChangePage("#activity_detail",{ transition: "slide",reverse: false,changeHash: false});
    }).on('click', '#newsroom_nowRegister', function(evt) {
        /*console.log('当前选中的活动 %o', v_news[$(this).parent().index()]);
        activityRegister.setAcvtivities(v_news[$(this).parent().index()]);
        activityRegister.from('#newsroom');
        $.mobile.newChangePage('#activityRegister',{ transition: "slide",reverse: false, changeHash:false});*/
        // Nick disable click event for scrolling start
        if (isScrolling) return false;
        // Nick disable click event for scrolling end
    	var _activity = v_news[$(this).parent().index()]; 
        console.log('当前选中的活动 %o',_activity);
        var _activityFlag = _activity['flag'];
        if(!_activityFlag){
	        activityRegister.setAcvtivities(_activity);
	        activityRegister.from('#newsroom');
	        $.mobile.newChangePage('#activityRegister',{ transition: "slide",reverse: false, changeHash:false});
        }else{
        	if(_activityFlag=='activity.deadTime'){
        		dia.alert("Oops!","You are too late! The registration of the activity is already closed.", ['OK'], function () {
				         return false;
				 });
        	}else if(_activityFlag=='activity.limitNum'){
        		dia.alert("Oops!","Sorry but your registration cannot be processed now as the activity has reached its maximum capacity.", ['OK'], function () {
				         return false;
				 });
        	}else if(_activityFlag=='activity.appIsTwo'){
        		dia.alert("Oops!","Looks like you have already registered this activity!", ['OK'], function () {
			         return false;
				 });
        	}else{
        		dia.alert("Oops!","Looks like have other issues. please contact #red help center!", ['OK'], function () {
			         return false;
				 });
        	}
        }
    });

    // 展示的时候请求新闻
    $("#newsroom").on( "pageshow", function( event ) {
        //
        console.log('newsroom show....');
        // Nick added for pull to refresh start
        disableClickEvent(true);
        // Nick added for pull to refresh end
        // Nick removed for pull to refresh start
        // currentPageNumer = 1;
        // Nick removed for pull to refresh end

		window.setBodyOverflow($(document.body));
        
        $('#news_content').css('height',($(window).height()-40));

		$('#newsroom_detailed_listview').empty();
		
        displayFilter();

        // Nick removed for pull to refresh start
        // $('#newsroom_listview_news').empty();
        // v_news = [];
        // getNews();
        // Nick removed for pull to refresh end
        // Nick added for pull to refresh start
        // Global variable to save the refresh status
        if (window.shouldPageRefresh.newsroom) {
            getNews(true);
        }
        // Nick added for pull to refresh end

        //页面滚动到底部自动加载新闻
        // Nick removed for pull to refresh start
        // $('#news_content').on('scroll', function() {

        //     if ((($(this).scrollTop() + $(this).height()) >= ($(this).children(':first-child').height() - 20)
        //         || ($(this).scrollTop() + $(this).height()) >= ($(this).children(':first-child').height() + 20))
        //         && scrollButtomOn == 0
        //         && $(this).scrollTop() - scrollTopBefore > 0) {
        //         // 禁用开关3秒钟
        //         disableScrollBottom();

        //         console.log('bottom');
        //         getNews();
        //     }

        //     scrollTopBefore = $(this).scrollTop();
        // });
        // Nick removed for pull to refresh end
		
		window.historyView = [];
    });

    // 消失的时候删除新闻
    // Nick removed for pull to refresh start
    // $("#newsroom").on( "pagehide", function( event ) {
    //     $('#newsroom_listview_news').empty();
    //     $('#news_content').off('scroll');
    // });
    // Nick removed for pull to refresh end

    // Nick added for pull to refresh start
    function cleanUpListItems() {
        $("#newsroom_listview_news").empty();
        $("#activities_listview_news").empty();
    }

    function stopEventPropagation(event) {
        event.stopPropagation();
    }

    function initPageLoading(wrapper) {
        var $wrapper = $("#" + wrapper),
            $pullDownEl = $wrapper.find("#pullDown"),
            $pullDownLabel = $pullDownEl.find(".pullDownLabel");

        if ($wrapper.find("ul").html()) {
            $wrapper.find(".scroller").css(window.getVendorStyle("transform"), "translate(0, 0)");
            $pullDownEl.attr("class", "loading");
            $pullDownLabel.text("Loading...");
        }
    }

    function disableClickEvent(addListener) {
        var $disabledBody = $("body.disabled");
        if ($disabledBody.length > 0) {
            if (addListener) {
                $disabledBody[0].addEventListener("click", stopEventPropagation, true);
            } else {
                $disabledBody[0].removeEventListener("click", stopEventPropagation, true);
                $disabledBody.removeClass("disabled");
            }
        }
    }
    // Nick added for pull to refresh end

    //推出activities 页面
    $('#push_activities').on('click', function(evt) {
        // Nick added for pull to refresh start
        initPageLoading("activities_wrapper");
        // Nick added for pull to refresh end
        $.mobile.newChangePage("#activities",{ transition: "slide",reverse: false,changeHash: false});
    });

    //推出setting页面
    $('#push_setting').on('click', function(evt) {
        $.mobile.newChangePage("#setting",{ transition: "slide",reverse: false,changeHash: false});
    });

    //推出Tilter页面
    $('#newsroom_btn_filter').on('click',function() {
        $.mobile.newChangePage("#filter",{ transition: "slide",reverse: false,changeHash: false});
    });

    //新闻搜索
    $('#new_search').off('click');
    $('#new_search').on('click', function() {

        console.log("新闻搜索页面");
        // 隐藏菜单和过滤，搜索
        $('#newsroom_header_title').css('display', 'none'); // block
        $('#newsroom_btn_menu').css('display', 'none'); // inline
        $('#newsroom_header_buttons').css('display', 'none'); //block
        // 展示搜索
        var li = '\<div>\
                <form id="newsroom_header_searchbar_form" style="width: 75%;float: left;margin: auto 0px auto 10px" action="javascript:void(0);"><input id="newsroom_header_searchbar" type="text" style="margin-top: 5px;width: 100%;border: solid 0px rgb(255,0,0);"/></form>\
                <input id="newsroom_header_cancel" style="width: 50px;float: left;padding: 0px;margin: 9px 0px 9px 10px;background-color: rgba(0,0,0,0);border: none;color: white;font-size: 14px;" type="button" value="Cancel" />\
            </div>';
        $('#newsroom_header').append(li);

        $('#newsroom_header_cancel').off('click')
            .on('click', function() {
                $('#newsroom_header_searchbar').remove();
                $('#newsroom_header_cancel').remove();
                $('#newsroom_header_searchbar_form').remove();
                $('#newsroom_header_title').css('display', 'block');
                $('#newsroom_btn_menu').css('display', 'inline');
                $('#newsroom_header_buttons').css('display', 'block');
                // Nick add for refreshing list after click "Cancel" start
                initPageLoading("news_wrapper");
                getNews(true);
                // Nick add for refreshing list after click "Cancel" end
            });

        $('#newsroom_header_searchbar').off('keyup')
            .on('keyup', function(evt) {
                if (evt.keyCode == 13) {
                    // Nick removed for pull to refresh start
                    // currentPageNumer = 1;
                    // $('#newsroom_listview_news').empty();
                    // getNews();
                    // Nick removed for pull to refresh start
                    // Nick added for pull to refresh start
                    initPageLoading("news_wrapper");
                    getNews(true);
                    // Nick added for pull to refresh end
                }
            });
    });

    function compatibility() {
        /* Logon */
        $('#newsroom_header_title').parent()
            .css('display', 'block')
            .css('postion', 'relative');

        $('#newsroom_header_title').css('postion', 'absulute')
            .css('width', '87px')
            .css('height','20px')
            .css('margin', '8px auto auto auto');
    }

    $(document).ready(function() {
        // 兼容其他浏览器
        compatibility();

        $('.ui-panel-inner').css({'padding':'0px'});
    });

    return {
        templateNews : function(img, title, content, timestamp, tags) {
            return createNews(img, title, content, timestamp, tags);
        }
    }
});